package team.knowers.qzh.qzhserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import team.knowers.qzh.qzhserver.common.database.BaseDO;
import team.knowers.qzh.qzhserver.dao.entity.CourseContentDO;
import team.knowers.qzh.qzhserver.dao.entity.CourseDO;
import team.knowers.qzh.qzhserver.dao.entity.SectionDO;
import team.knowers.qzh.qzhserver.dao.mapper.SectionMapper;
import team.knowers.qzh.qzhserver.dto.resp.*;
import team.knowers.qzh.qzhserver.service.SectionService;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SectionServiceImpl extends ServiceImpl<SectionMapper, SectionDO> implements SectionService {
    /**
     * 作者原创的章节的目录
     */
    @Override
    public List<SectionDetailsRespDTO> getSectionDetailsById(Long chapterId) {
        LambdaQueryWrapper<SectionDO> queryWrapper = Wrappers.lambdaQuery(SectionDO.class)
                .eq(SectionDO::getChapterId, chapterId)
                .eq(SectionDO::getDelFlag, 0)
                .eq(SectionDO::getVersion, 0)
                .orderByAsc(SectionDO::getOrder);
        List<SectionDO> sectionDO = baseMapper.selectList(queryWrapper);
        List<SectionDetailsRespDTO> results = new ArrayList<>();
        for (SectionDO sectionDO1 : sectionDO) {
            results.add(BeanUtil.toBean(sectionDO1, SectionDetailsRespDTO.class));
        }
        return results;
    }

    @Override
    public List<VersionSectionRespDTO> listMultiVersionSectionBySectionNumber(Long sectionNumber) {
        LambdaQueryWrapper<SectionDO> queryWrapper = Wrappers.lambdaQuery(SectionDO.class)
                .eq(SectionDO::getSectionNumber, sectionNumber)
                .eq(SectionDO::getDelFlag, 0)
                .orderByDesc(SectionDO::getLikes);
        List<SectionDO> sectionDO = baseMapper.selectList(queryWrapper);
        List<VersionSectionRespDTO> results = new ArrayList<>();
        for (SectionDO sectionDO1 : sectionDO) {
            results.add(BeanUtil.toBean(sectionDO1, VersionSectionRespDTO.class));
        }
        return results;
    }

    @Override
    public List<SectionRecentRespDTO> homeUserVersionByTimeDesc(Long userId) {
        LambdaQueryWrapper<SectionDO> queryWrapper = Wrappers.lambdaQuery(SectionDO.class).eq(SectionDO::getDelFlag, 0).eq(SectionDO::getAuthorId, userId).orderByDesc(BaseDO::getCreateTime).ne(SectionDO::getVersion, 0);
        List<SectionDO> courseDOS = baseMapper.selectList(queryWrapper);
        List<SectionRecentRespDTO> results = new ArrayList<>();
        for (SectionDO each : courseDOS) {
            results.add(BeanUtil.toBean(each, SectionRecentRespDTO.class));
        }
        return results;
    }
}
